import 'dart:convert';
import 'dart:io';
import 'dart:developer'; // 引入 log 方法
import 'package:http/http.dart' as http;
import 'package:crypto/crypto.dart';
import 'package:intl/intl.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart'; // 引入 flutter_dotenv

class HealthDataService {
  // DeepSeek API 配置
  static const _deepseekUrl = 'https://api.deepseek.com/v1/chat/completions';
  static final _deepseekApiKey = dotenv.env['DEEPSEEK_API_KEY']!;

  // 讯飞 OCR API 配置
  static const _xfOcrUrl = 'https://api.xf-yun.com/v1/private/sf8e6aca1';
  static const host = "api.xfyun.com";
  static const requestLine = "POST /v1/private/sf8e6aca1 HTTP/1.1";
  static final _xfAppId = dotenv.env['XF_APP_ID']!; // 替换为你自己的讯飞 APPID
  static final _xfApiKey = dotenv.env['XF_API_KEY']!; // 替换为你自己的讯飞 APIKey
  static final _xfApiSecret = dotenv.env['XF_API_SECRET']!; // 替换为你自己的讯飞 APISecret

  /// 调用 DeepSeek 服务解析健康数据
  static Future<Map<String, dynamic>> parseHealthData(String ocrText) async {
    final headers = {
      'Authorization': 'Bearer $_deepseekApiKey',
      'Content-Type': 'application/json',
    };

    const systemPrompt = '''你是一个专业健康数据分析助手，请按以下要求处理：
1. 从文本提取以下数值字段：weight, water, fat, protein, bone_mass, 
body_fat_rate, bmi, visceral_fat_level, basal_metabolism
2. 返回严格合规的JSON，只包含数值
3. 示例：{"weight": 70.5, "bmi": 22.1}''' ;

    final payload = {
      "model": "deepseek-chat",
      "messages": [
        {"role": "system", "content": systemPrompt},
        {"role": "user", "content": ocrText}
      ],
      "response_format": {"type": "json_object"}
    };

    final response = await http.post(
      Uri.parse(_deepseekUrl),
      headers: headers,
      body: jsonEncode(payload),
    );

    if (response.statusCode == 200) {
      return _parseResponse(response.body);
    } else {
      throw Exception('健康数据解析失败: ${response.body}');
    }
  }

   /// 调用讯飞 OCR 服务识别图片中的文字
  static Future<String> recognizeTextFromImage(File image) async {
    // 生成时间戳
    final date = DateFormat('EEE, dd MMM yyyy HH:mm:ss \'GMT\'', 'en_US')
        .format(DateTime.now().toUtc());

    // 构建签名原始字符串
    final signatureOrigin = 'host: api.xf-yun.com\n'
        'date: $date\n'
        'POST /v1/private/sf8e6aca1 HTTP/1.1';

    // 使用 HMAC-SHA256 加密生成签名
    final hmacSha256 = Hmac(sha256, utf8.encode(_xfApiSecret));
    final signatureSha = base64Encode(hmacSha256.convert(utf8.encode(signatureOrigin)).bytes);

    // 构建 Authorization 字段
    final authorizationOrigin =
        'api_key="$_xfApiKey", algorithm="hmac-sha256", headers="host date request-line", signature="$signatureSha"';
    final authorization = base64Encode(utf8.encode(authorizationOrigin));

    // 使用 log 打印调试信息
    log('Date: $date', name: 'HealthDataService');
    log('Signature Origin: $signatureOrigin', name: 'HealthDataService');
    log('Authorization Origin: $authorizationOrigin', name: 'HealthDataService');
    log('Authorization (Base64): $authorization', name: 'HealthDataService');

    // 读取图片并转换为 Base64
    final imageBytes = await image.readAsBytes();
    final base64Image = base64Encode(imageBytes);

    // 构建请求头
    final headers = {
      'Content-Type': 'application/json',
      'Host': 'api.xf-yun.com',
      'Date': date,
      'Authorization': authorization,
    };

    // 使用 log 打印请求头
    log('Headers: $headers', name: 'HealthDataService');

    // 构建请求体
    final payload = {
      'header': {
        'app_id': _xfAppId,
        'status': 3,
      },
      'parameter': {
        'sf8e6aca1': {
          'category': 'ch_en_public_cloud',
          'result': {
            'encoding': 'utf8',
            'compress': 'raw',
            'format': 'json',
          }
        }
      },
      'payload': {
        'sf8e6aca1_data_1': {
          'encoding': 'jpg',
          'image': base64Image,
          'status': 3,
        }
      },
    };

    // 使用 log 打印请求体
    log('Payload: ${jsonEncode(payload)}', name: 'HealthDataService');

    // 构建请求 URL
    final requestUrl = Uri.parse(_xfOcrUrl);

    // 发送请求
    final response = await http.post(
      requestUrl,
      headers: headers,
      body: jsonEncode(payload),
    );

    // 使用 log 打印响应信息
    log('Response Status Code: ${response.statusCode}', name: 'HealthDataService');
    log('Response Body: ${response.body}', name: 'HealthDataService');

    if (response.statusCode == 200) {
      final jsonResponse = jsonDecode(response.body);
      final textBase64 = jsonResponse['payload']['result']['text'];
      final decodedText = utf8.decode(base64Decode(textBase64));
      return decodedText; // 返回解码后的文字
    } else {
      throw Exception('讯飞 OCR 识别失败: ${response.body}');
    }
  }

  /// 解析 DeepSeek 响应
  static Map<String, dynamic> _parseResponse(String responseBody) {
    final jsonData = jsonDecode(responseBody);
    final content = jsonData['choices'][0]['message']['content'];
    return jsonDecode(content);
  }
}
